/*
 * Copyright 2007-2008 Brian Cavalier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.bc.iterate.view;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.MatchResult;

/**
 * ScannerView is a wrapper for the very useful java.util.Scanner class that
 * allows iteration over pattern matches.
 * 
 * @author Brian Cavalier
 * @see Iterator
 * @see Iterable
 * @see org.bc.iterate.Iterate
 * @see org.bc.iterate.Grep
 */
public class ScannerView extends AbstractView<MatchResult> {
	private Pattern pattern;
	private Scanner scanner;
	private String nextMatch;
	
	public ScannerView(InputStream in) {
		scanner = new Scanner(in);
	}

    public ScannerView(Pattern pattern)
    {
        this.pattern = pattern;
    }

    public ScannerView setPattern(String pattern) {
		return setPattern(Pattern.compile(pattern));
	}

	public ScannerView setPattern(Pattern pattern) {
		this.pattern = pattern;
		return this;
	}

	public boolean hasNext() {
        //noinspection WhileLoopSpinsOnField
        while(nextMatch == null) {
			nextMatch = scanner.findInLine(pattern);
			if(nextMatch == null) {
                //noinspection CatchGenericClass
                try {
					scanner.nextLine();
				}
				catch(Exception ignored) {
					return false;
				}
			}
		}
		return true;
	}
	
	@SuppressWarnings({"IteratorNextCanNotThrowNoSuchElementException"})
    public MatchResult next() {
		if(nextMatch != null) {
			nextMatch = null;
			return scanner.match();
		}
		else {
			return null;
		}
	}
}